import {
  formatDateTime,
  debounce
} from "../utils/util"
import { request } from '@/utils/request'
/**
 * @同意隐私整车
 */
export const agreePolicy = () => {
  const app = getApp();
  app.globalData.policyUpdate = false;
  app.globalData.policyMessage = "";
  app.globalData.policyType = "";
  app.globalData.policyDate = "";

  const token = wx.getStorageSync('usertoken');
  return new Promise(resolve => {
    app.reqFin({
      url: "/foreApi/agreement/getConfirmStatus",
      method: "post",
      header: {
        "token": token
      },
      data: {
        confirmStatus: 1
      },
      complete: () => {
        resolve(null)
      }
    })
  })
}

/**
 * @不同意隐私政策
 */
export const disAgreePolicy = () => {
  const app = getApp();
  app.globalData.policyUpdate = false;
  app.globalData.policyMessage = "";
  app.globalData.policyType = "";

  exitLogin();
}
/**
 * @获取隐私更新
 */
export const getPolicyUpdate = debounce((app) => {
  app = app ? app : getApp();

  const token = wx.getStorageSync('usertoken');

  if (token) {
    app.reqFin({
      url: "/foreApi/agreement/getAgreementPolicy",
      method: "post",
      header: {
        "token": token
      },
      success: (res) => {
        if (res.data.code === 1) {
          const {
            confirmStatus,
            promptText,
            updateType,
            creatAt
          } = res.data.data;

          if (confirmStatus === 0) { 
            app.globalData.policyMessage = promptText;
            app.globalData.policyType = updateType;
            app.globalData.policyDate = formatDateTime(creatAt, "yyyy-MM-dd");
            app.globalData.policyUpdate = true;
          }
        }
      }
    })
  }
}, 800);

/**
 * @获取企微销售二维码
 */
export const getSalesWechatInfo = async (app) => {
  app = app ? app : getApp();
  app.globalData.salesWechatInfo = {
    salesWechatQrcode: "",
    salesWechatEmployeeCode: "",
    salesWechatUserName: ""
  }
  app.globalData.salesWechatQrcodePower = "UNDONE";

  const token = wx.getStorageSync('usertoken');

  if (token) {
    /**
     * @完全放开后这段逻辑可删除
     */
    let shouldGetQrcode = false;
    const powerRes = await getMemberPower(false, app);

    if(powerRes.status) {
      const powers = powerRes.powers;

      if(powers.indexOf("12-313") >= 0) {
        shouldGetQrcode = true;
      }
    }
    if(!shouldGetQrcode) {
      app.globalData.salesWechatInfo = {
        salesWechatQrcode: "",
        salesWechatEmployeeCode: "",
        salesWechatUserName: ""
      }
      app.globalData.salesWechatQrcodePower = "N";
      return;
    }
    //

    app.reqFin({
      url: "/appletApi/user/getSaleQrcodeOrInfo",
      method: "post",
      header: {
        "token": token
      },
      success: (res) => {
        if (res.data.code === 1 && res.data.data && (res.data.data.code || res.data.data.employeeCode)) {

          const { code, employeeCode, userName } = res.data.data;

          let qrcode = "";
          let employeeNo = "";
          let employeeUserName = "";

          if(code) {
            let response = null;
            try {
              response = JSON.parse(code)
            } catch(e) {
  
            }

            if(response && response.code === 200 && response.data && response.data.value && response.data.value[0] && response.data.value[0].qr_code) {
              qrcode = response.data.value[0].qr_code;
            }
          } else {
            employeeNo = employeeCode ? employeeCode : "";
            employeeUserName = userName ? userName : "";
          }

          app.globalData.salesWechatInfo = {
            salesWechatQrcode: qrcode,
            salesWechatEmployeeCode: employeeNo,
            salesWechatUserName: employeeUserName
          }
          app.globalData.salesWechatQrcodePower = (qrcode || employeeNo || employeeUserName) ? "Y" : "N";
        } else {
          app.globalData.salesWechatInfo = {
            salesWechatQrcode: "",
            salesWechatEmployeeCode: "",
            salesWechatUserName: ""
          }
          app.globalData.salesWechatQrcodePower = "N";
        }
      },
      fail: () => {
        app.globalData.salesWechatInfo = {
          salesWechatQrcode: "",
          salesWechatEmployeeCode: "",
          salesWechatUserName: ""
        }
        app.globalData.salesWechatQrcodePower = "N";
      }
    })
  } else {
    app.globalData.salesWechatInfo = {
      salesWechatQrcode: "",
      salesWechatEmployeeCode: "",
      salesWechatUserName: ""
    }
    app.globalData.salesWechatQrcodePower = "N";
  }
}

/**
 * @获取微信公众号关注情况
 */
export const getOfficialAccountFollow = debounce((app) => {
  app = app ? app : getApp();

  wx.login({
    success: (res) => {
      app.reqFin({
        url: "/foreApi/public/subscribeStatus",
        method: "post",
        header: {
          "wx-token": "9F865C7ACAF32AAF7D543CB36F9E1CF7"
        },
        data: {
          jsCode: res.code
        },
        success: (res) => {
          if (res.data.code === 1 && res.data.data) {
            const subscribe = res.data.data.subscribe;

            if (subscribe === 0) {
              app.globalData.officialAccountFollow = true;
            }
          } else {
            app.globalData.officialAccountFollow = true;
          }
        },
        fail: () => {
          app.globalData.officialAccountFollow = true;
        }
      })
    }
  })
}, 500)

/**
 * @退出登录
 */
export const exitLogin = async function () {
  const app = getApp();

  let token = wx.getStorageSync('usertoken');

  await deleteOpenId();

  app.reqFin({
    url: '/appletApi/user/exit',
    method: 'post',
    header: {
      'Content-Type': 'application/json',
      'token': token
    },
    data: {},
    success: (res) => {
      if (res.data.code == 1) {
        removeStorage();
        wx.reLaunch({
          url: '/pages/home/index',
        })

        return
      } else { // token失效
        wx.reLaunch({
          url: '/pages/home/index',
        })

        return
      }
    },
    fail: () => {
      wx.reLaunch({
        url: '/pages/home/index',
      })
    }
  })
}

/**
 * @删掉openId关联
 */
export const deleteOpenId = () => {
  return new Promise(resolve => {
    const app = getApp();

    let token = wx.getStorageSync('usertoken');

    app.reqFin({
      url: '/appletApi/user/getUserInfo',
      method: 'post',
      header: {
        "token": token
      },
      // 获取用户信息成功
      success: (res) => {
        if (res.data.code == 1) {
          const {
            phone
          } = res.data;

          let openId = wx.getStorageSync('openid');

          app.reqZS({
            url: '/fw/user/delete?openId=' + openId + "&phone=" + phone,
            method: 'delete',
            header: {
              'Content-Type': 'application/json',
              "token": token
            },

            data: {},
            complete: () => {
              resolve(null);
            }
          })

        } else { // token失效
          wx.reLaunch({
            url: '/pages/home/index',
          })

          return
        }
      },
      fail: () => {
        wx.reLaunch({
          url: '/pages/home/index',
        })
      }
    })
  })
}

/**
 * @移除缓存
 */
export const removeStorage = () => {
  const app = getApp();

  app.globalData.isLogin = false
  //清除token
  wx.removeStorage({
    key: 'usertoken',
    success(res) {}
  })
  //清除authStatus
  wx.removeStorage({
    key: 'authStatus',
    success(res) {}
  })
  //清除分享的销售码
  wx.removeStorage({
    key: 'recommendCode',
    success(res) {}
  })
  //清除销售码
  wx.removeStorage({
    key: 'myRecommendCode',
  })
  //清除手机号
  wx.removeStorage({
    key: 'phoneNumber'
  })
  wx.removeStorage({
    key: 'userid',
  })
  app.globalData.salesWechatQrcodePower = "N";
  app.globalData.salesWechatQrcode = "";
}

const createCityListFactory = () => {
  let cityList = null;

  return function () {
    return new Promise(resolve => {
      if (cityList) {
        resolve(cityList)
        return;
      }

      var token = wx.getStorageSync('usertoken');
      const app = getApp();

      app.reqFin({
        url: '/appletApi/reservation/getProvinceCities',
        method: 'post',
        header: {
          "token": token
        },
        data: {},
        success: (res) => {
          if (res.data.code == 1) {
            res.data.data[0].cities.forEach(item => {
              if (item.cities.length == 0) {
                delete item.cities
              }
            })

            cityList = res.data.data;

            resolve(res.data.data)
          } else {
            resolve(null)
          }
        },
        fail: () => {
          resolve(null)
        }
      })
    })
  }
}

export const getCityList = createCityListFactory();

/**
 * @匹配流程状态名称
 * @param {*} flowStatus 
 */
export const mapFlowStatusName = (flowStatus) => {
  let result = "异常";
  switch (flowStatus) {
    case 0:
      result = "草稿";
      break;
    case 1:
      result = "需求审批中";
      break;
    case 2:
      result = "审批通过，处理中";
      break;
    case 3:
      result = "交付确认中";
      break;
    case 4:
      result = "已交付待打分";
      break;
    case 5:
      result = "已完结";
      break;
    case 6:
      result = "已驳回";
      break;
    case 7:
      result = "交付确认中（需求方）";
      break;
    case 8:
      result = "已撤回";
      break;
    default:
      break;
  }

  return result;
}

/**
 * @匹配流程状态颜色
 * @param {*} flowStatus 
 */
export const mapFlowStatusColor = (flowStatus) => {
  let result = "";
  switch (flowStatus) {
    case 0:
      result = "yellow";
      break;
    case 1:
      result = "blue";
      break;
    case 2:
      result = "blue";
      break;
    case 3:
      result = "blue";
      break;
    case 4:
      result = "blue";
      break;
    case 5:
      result = "green";
      break;
    case 6:
      result = "red";
      break;
    case 7:
      result = "blue";
      break;
    case 8:
      result = "red";
      break;
    default:
      break;
  }

  return result;
}

/**
 * @获取邀请函状态
 * @状态枚举
 * { status: "none", message: "", signTime: null }
 * none-未提交
 * approval-审批中
 * agree-审批通过
 * reject-审批驳回
 * expire-已失效
 * unkonwn-未知(error)
 */
export const getQuestStatus = () => {
  return new Promise(resolve => {
    var token = wx.getStorageSync('usertoken');
    const app = getApp();

    let defaultStatus = 'none';

    app.reqFin({
      url: '/appletApi/memberQuestion/tip',
      method: 'post',
      header: {
        'Content-Type': 'application/json',
        "token": token
      },
      data: {
        questId: 100
      },
      success: (res) => {
        console.log("res：", res);

        if (res.data.code === 1) {
          const code = res.data.data ? res.data.data.result : null;
          const signTime = res.data.data ? res.data.data.signTime : null;
          const imageSrc = res.data.data ? res.data.data.pic : "";

          const {
            status,
            message
          } = mappingCodeStatusMessage(code, res.data.message);

          resolve({
            status,
            signTime,
            imageSrc,
            message
          })
        } else {
          resolve({
            status: "unknown",
            signTime: null,
            imageSrc: "",
            message: res.data.message ? res.data.message : "未知错误"
          })
        }
      },
      fail: (err) => {
        console.log("err：", err);

        resolve({
          status: "unknown",
          signTime: null,
          imageSrc: "",
          message: "未知异常"
        });
      }
    })
  })
}

/**
 * @映射code和status
 * @param {*} code 
 * @param {*} message 
 */
export const mappingCodeStatusMessage = (code, message) => {
  let status = "unknown";
  let dataMessage = "";

  switch (code) {
    case 5:
      status = "none";
      break;
    case 6:
      status = "expire";
      break;
    case 7:
      status = "notStarted"
      break;
    case 3:
      status = "approval";
      break;
    case 2:
      status = "reject";
      dataMessage = message ? message : "预约报名失败，请重新报名";
      break;
    case 1:
      status = "agree";
      break;
    case 4:
      status = "unknown";
      dataMessage = message ? message : "问卷不存在";
      break;
    default:
      status = "unknown";
      dataMessage = message ? message : "未知异常";
      break;
  }

  return {
    status,
    message: dataMessage
  }
}

/**
 * @获取我的信息
 */

  export const getUserInfo = () => request.post('/wxapi/appletApi/user/getUserInfo').then(res => {
    let result = {
      status: false,
      userInfo: {},
      isLogin: false,
      tipsFlag: false,
      message: "获取用户信息失败"
    }
    if (res.data.status == '401') {
          // wx.removeStorageSync('usertoken');
          // result = {
          //   status: false,
          //   userInfo: {},
          //   isLogin: false,
          //   tipsFlag: false,
          //   mesage: "登录已失效",
          // }
          // resolve(result)
        }
        if (res.data.code === 1) {
          result = {
            status: true,
            userInfo: res.data,
            isLogin: true,
            tipsFlag: false,
            message: ""
          }
        } else if (res.data.code === 3003) {
          result = {
            status: false,
            userInfo: {},
            isLogin: false,
            tipsFlag: true,
            message: ""
          }
        } else {
          const message = res.data.message ? res.data.message : "获取用户信息失败"
          result = {
            status: false,
            userInfo: {},
            isLogin: true,
            tipsFlag: false,
            message: message
          }
        }

        return result;
  }).catch(err => {
    return {
      status: false,
      userInfo: {},
      isLogin: false,
      tipsFlag: false,
      message: "获取用户信息失败"
    }
  })

/**
 * @获取用户权限码
 */
  export const getMemberPower = () => request.post('/wxapi/foreApi/getMemberPower').then(res => {
    let result = {
      status: false,
      powers: "",
      isLogin: false,
      message: "获取权限码失败"
    }
        if (res.data.code === 1) {
          result = {
            status: true,
            powers: res.data.powers,
            isLogin: true,
            message: ""
          }
        } else {
          const message = res.data.message ? res.data.message : "获取权限码失败"
          result = {
            status: false,
            powers: "",
            isLogin: true,
            message: message
          }
        }
        return result;
  }).catch(err => {
    return {
      status: false,
      powers: "",
      isLogin: false,
      message: "获取权限码失败"
    }
  })


/**
 * @获取用户权限
 */
export const getFlowPermission = function (flowType, options = {}, autoLogin = false) {
  return new Promise(resolve => {
    const app = getApp();

    let result = {
      status: false,
      isLogin: false,
      message: "获取权限失败"
    }

    var token = wx.getStorageSync('usertoken');

    if (!token) {
      result.message = "当前未登录"
      resolve(result);
      return;
    }

    app.reqFin({
      url: '/foreApi/public/checkLongImgPower',
      method: 'post',
      header: {
        "token": token
      },
      data: {
        ...options,
        flowType
      },
      success: (res) => {
        if (res.data.status == '401') {
          wx.removeStorageSync('usertoken');
          result = {
            status: false,
            isLogin: false,
            mesage: "登录已失效",
          }
          if (autoLogin) {
            wx.showToast({
              title: '登录已失效',
              duration: 2000
            })
            const timer = setTimeout(() => {
              wx.reLaunch({
                url: '/pages/login/index',
              })
              clearTimeout(timer);
            }, 1500)
          }
          resolve(result)
        }
        if (res.data.code === 1) {
          result = {
            status: true,
            isLogin: true,
            message: ""
          }
        } else {
          const message = res.data.message ? res.data.message : "暂无查看权限"
          result = {
            status: false,
            isLogin: true,
            message: message
          }
        }

        resolve(result);
      },
      fail: () => {
        resolve(result);
      }
    });
  })
}


/**
 * @获取销售信息
 * @param {*} autoLogin 
 */
export const getSaleInfo = function (autoLogin = false) {
  return new Promise(resolve => {
    const app = getApp();

    let result = {
      status: false,
      saleInfo: {},
      isLogin: false,
      message: "获取销售信息失败"
    }

    var token = wx.getStorageSync('usertoken');

    if (!token) {
      resolve(result);
      return;
    }

    app.reqFin({
      url: '/foreApi/userSaleInfo',
      method: 'post',
      header: {
        "token": token
      },
      success: (res) => {
        if (res.data.status == '401') {
          wx.removeStorageSync('usertoken');
          result = {
            status: false,
            powers: "",
            isLogin: false,
            mesage: "登录已失效",
          }
          if (autoLogin) {
            wx.showToast({
              title: '登录已失效',
              duration: 2000
            })
            const timer = setTimeout(() => {
              wx.reLaunch({
                url: '/pages/login/index',
              })
              clearTimeout(timer);
            }, 1500)
          }
          resolve(result)
        }
        if (res.data.code === 1) {
          result = {
            status: true,
            saleInfo: res.data,
            isLogin: true,
            message: ""
          }
        } else {
          const message = res.data.message ? res.data.message : "获取销售信息失败"
          result = {
            status: false,
            saleInfo: {},
            isLogin: true,
            message: message
          }
        }

        resolve(result);
      },
      fail: () => {
        resolve(result);
      }
    });
  })
}

/**
 * @定义全局属性的监听任务
 * @重复定义一个全局属性的监听任务会覆盖当前属性的所有监听函数
 * @param {*} globalDataProperty 
 * @param {*} defaultValue 
 */
export const defineGlobalDataListener = (globalDataProperty, defaultValue = null, app) => {
  app = app ? app : getApp();
  const listenerCallbackFactory = app.globalData.listenerCallbackFactory;
  listenerCallbackFactory[globalDataProperty] = {};

  let _globalDataValue = defaultValue;
  Object.defineProperty(app.globalData, globalDataProperty, {
    configurable: true,
    enumerable: true,
    //添加存取属性，当读取属性值时，调用get方法
    get: () => {
      return _globalDataValue;
    },
    //当设置属性时，调用set方法
    set: (v) => {
      const preValue = _globalDataValue;
      _globalDataValue = v;
      const globalDataCallbacks = listenerCallbackFactory[globalDataProperty];
      Object.keys(globalDataCallbacks).forEach(routeKey => {
        globalDataCallbacks[routeKey](v, {
          routeKey: routeKey,
          preValue: preValue
        });
      })
    }
  });
}

/**
 * @定义一个全局属性的监听函数
 * @一个页面针对一个全局属性只能定义一个监听函数
 * @重复定义会覆盖
 * @param {*} globalDataProperty 
 */
export const watchGlobalDataListener = (globalDataProperty, fn) => {
  const app = getApp();
  const listenerCallbackFactory = app.globalData.listenerCallbackFactory;

  const globalDataCallbacks = listenerCallbackFactory[globalDataProperty];

  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const routeKey = currentPage.route;

  globalDataCallbacks[routeKey] = fn;
}